package com.icesoft.framework.core.util;

import com.icesoft.framework.core.vo.JsonResult;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;

@Slf4j
public abstract class ResponseUtils {

	public static void writeJson(HttpServletResponse response, JsonResult<?> resp) {
		response.setCharacterEncoding("utf8");
		response.setContentType("application/json");
		writeValue(response, resp.toJson());
	}

	public static void writeJson(HttpServletResponse response, JsonResult<?> resp, int status) {
		response.setCharacterEncoding("utf8");
		response.setContentType("application/json");
		response.setStatus(status);
		writeValue(response, resp.toJson());
	}

	public static void writeValue(HttpServletResponse response, String value) {
		response.setCharacterEncoding("utf8");
		try {
			PrintWriter out = response.getWriter();
			out.write(value);
			out.flush();
			out.close();
		} catch (IOException e) {
			log.error("writeValue error", e);
		}
	}

	/**
	 * @param fileName 下载的自定义文件名
	 */
	public static void writeToFileStream(HttpServletResponse response, String fileName, InputStream is)
			throws IOException {
		writeToFileStream(response, fileName, is, "application/octet-stream;charset=UTF-8");
	}

	public static void writeToFileStream(HttpServletResponse response, String fileName, InputStream is,
										 String contentType) throws IOException {
		response.reset();
		response.setHeader("Content-Disposition",
				"attachment; filename=\"" + new String(fileName.getBytes(), StandardCharsets.ISO_8859_1) + "\"");
		response.setContentType(contentType);
		writeStream(response, is);
	}

	public static void writeStream(HttpServletResponse response, InputStream is)
			throws IOException {
		response.setCharacterEncoding("utf8");
		try (BufferedInputStream bis = new BufferedInputStream(is);
			 OutputStream outputStream = new BufferedOutputStream(response.getOutputStream())) {
			byte[] buffer = new byte[1024];
			int i = bis.read(buffer);
			while (i != -1) {
				outputStream.write(buffer, 0, i);
				i = bis.read(buffer);
			}
			outputStream.flush();
			is.close();
		}
	}
}
